//
//  ResizeableFormView.m
//  etionUI
//
//  Created by wangjian on 12/26/13.
//  Copyright (c) 2013 GuangZhouXuanWu. All rights reserved.
//

#import "ResizeableFormView.h"

#define CONTROL_SIZE 30
#define CONTROL_MARGIN 10
#define RESIZE_CTRL_LINE_W 2
#define RESIZE_CTRL_RADIUS 4

/**
 *  由于resize ctrl view会遮盖住下方的form view的触摸事件，所以用CFormResizeEventView来响应不影响下方事件接收的触摸事件
 */
@interface CFormResizeEventView : UIView

@property (nonatomic, assign) UIView *targetView;

@end

@implementation CFormResizeEventView

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [[self targetView] touchesBegan:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [[self targetView] touchesMoved:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [[self targetView] touchesCancelled:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [[self targetView] touchesEnded:touches withEvent:event];
}

@end

@implementation CFormResizeCtrlView
{
    CFormResizeEventView *eventView;
    
    BOOL resizeing;
    CGPoint prevPoint;
}

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        self.opaque = NO;
        self.userInteractionEnabled = NO;
        
        eventView = [[CFormResizeEventView alloc] initWithFrame:CGRectZero];
        eventView.targetView = self;
        
        self.renderColor = [UIColor flatDarkBlueColor];
    }
    return self;
}

- (void)dealloc
{
    [eventView release];
    [super dealloc];
}

- (void)didMoveToSuperview
{
    [super didMoveToSuperview];
    if (self.superview != nil)
    {
        [self.superview addSubview:eventView];
    }
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
    CGRect realClipRect = [self curRealClipRect];
    eventView.frame = CGRectMake(self.left+realClipRect.origin.x, self.top+realClipRect.origin.y, self.type == EFormControlViewTypeRow ? CGRectGetMaxX(self.anchorFrame)-CGRectGetMinX(self.frame)+CONTROL_MARGIN : realClipRect.size.width, self.type == EFormControlViewTypeRow ? realClipRect.size.height : CGRectGetMaxY(self.anchorFrame)-CGRectGetMinY(self.frame)+CONTROL_MARGIN);
    [self setNeedsDisplay];
}

- (void)setHidden:(BOOL)hidden
{
    [super setHidden:hidden];
    eventView.hidden = hidden;
}

- (void)setAnchorFrame:(CGRect)anchorFrame
{
    _anchorFrame = anchorFrame;
    [self reloadView];
}

- (void)setType:(EFormControlViewType)type
{
    _type = type;
    [self reloadView];
}

- (void)setContentSize:(CGSize)contentSize
{
    _contentSize = contentSize;
    [self reloadView];
}

- (void)reloadView
{
    if (_anchorFrame.size.width == 0 || _anchorFrame.size.height == 0)
    {
        self.frame = CGRectZero;
    }
    else
    {
        if (_type == EFormControlViewTypeRow)
        {
            self.frame = CGRectMake(CGRectGetMinX(self.anchorFrame)-RESIZE_CTRL_RADIUS, CGRectGetMinY(self.anchorFrame)-RESIZE_CTRL_LINE_W, _contentSize.width+CGRectGetWidth(self.anchorFrame)+CONTROL_MARGIN+RESIZE_CTRL_RADIUS+RESIZE_CTRL_LINE_W, _contentSize.height+2*RESIZE_CTRL_LINE_W);
        }
        else
        {
            self.frame = CGRectMake(CGRectGetMinX(self.anchorFrame)-RESIZE_CTRL_LINE_W, CGRectGetMinY(self.anchorFrame)-RESIZE_CTRL_RADIUS, _contentSize.width+2*RESIZE_CTRL_LINE_W, _contentSize.height+CGRectGetHeight(self.anchorFrame)+CONTROL_MARGIN+RESIZE_CTRL_RADIUS+RESIZE_CTRL_LINE_W);
        }
    }
}

- (CGRect)curRealClipRect
{
    CGRect realMaskFrame = CGRectInset(self.maskFrame, self.type == EFormControlViewTypeRow ? 0 : -(RESIZE_CTRL_LINE_W), self.type == EFormControlViewTypeRow ? -(RESIZE_CTRL_LINE_W) : 0);
    CGRect realClipRect = self.bounds;
    if (self.type == EFormControlViewTypeRow)
    {
        if (self.top < CGRectGetMinY(realMaskFrame))
        {
            realClipRect = self.bottom < CGRectGetMinY(realMaskFrame) ? CGRectZero : CGRectMake(0, CGRectGetMinY(realMaskFrame)-self.top, self.width, self.bottom-CGRectGetMinY(realMaskFrame));
        }
        else if (self.bottom > CGRectGetMaxY(realMaskFrame))
        {
            realClipRect = self.top > CGRectGetMaxY(realMaskFrame) ? CGRectZero : CGRectMake(0, 0, self.width, CGRectGetMaxY(realMaskFrame)-self.top);
        }
    }
    else
    {
        if (self.left < CGRectGetMinX(realMaskFrame))
        {
            realClipRect = self.right < CGRectGetMinX(realMaskFrame) ? CGRectZero : CGRectMake(CGRectGetMinX(realMaskFrame)-self.left, 0, self.right-CGRectGetMinX(realMaskFrame), self.height);
        }
        else if (self.right > CGRectGetMaxX(realMaskFrame))
        {
            realClipRect = self.left > CGRectGetMaxX(realMaskFrame) ? CGRectZero : CGRectMake(0, 0, CGRectGetMaxX(realMaskFrame)-self.left, self.height);
        }
    }
    
    return realClipRect;
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGFloat lineWidth = RESIZE_CTRL_LINE_W;
    CGFloat cornerRadius = RESIZE_CTRL_RADIUS;
    
    CGContextClearRect(context, rect);
    CGContextSetFillColorWithColor(context, self.renderColor.CGColor);
    CGContextSetLineWidth(context, 0);
    CGContextClipToRect(context, [self curRealClipRect]);
    
    if (self.type == EFormControlViewTypeRow)
    {
        //填充有两个圆角的头部
        rect = CGRectMake(0, 0, CGRectGetMaxX(self.anchorFrame)-CGRectGetMinX(self.frame), CGRectGetHeight(self.frame));
        CGContextMoveToPoint(context, CGRectGetMinX(rect) + cornerRadius, CGRectGetMinY(rect));
        CGContextAddLineToPoint(context, CGRectGetMaxX(rect), CGRectGetMinY(rect));
        CGContextAddLineToPoint(context, CGRectGetMaxX(rect), CGRectGetMaxY(rect));
        CGContextAddArc(context, CGRectGetMinX(rect) + cornerRadius, CGRectGetMaxY(rect) - cornerRadius, cornerRadius, M_PI / 2, M_PI, 0);
        CGContextAddArc(context, CGRectGetMinX(rect) + cornerRadius, CGRectGetMinY(rect) + cornerRadius, cornerRadius, M_PI, 3 * M_PI / 2, 0);
        CGContextFillPath(context);
        
        //绘制表示可拖拽的两个线条
        CGContextMoveToPoint(context, CGRectGetMinX(rect) + cornerRadius, self.isReverse == NO ? CGRectGetMaxY(rect)-10 : CGRectGetMinY(rect)+5);
        CGContextAddLineToPoint(context, CGRectGetMaxX(rect)-cornerRadius, self.isReverse == NO ? CGRectGetMaxY(rect)-10 : CGRectGetMinY(rect)+5);
        CGContextMoveToPoint(context, CGRectGetMinX(rect) + cornerRadius, self.isReverse == NO ? CGRectGetMaxY(rect)-5 : CGRectGetMinY(rect)+10);
        CGContextAddLineToPoint(context, CGRectGetMaxX(rect)-cornerRadius, self.isReverse == NO ? CGRectGetMaxY(rect)-5 : CGRectGetMinY(rect)+10);
        CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
        CGContextSetLineWidth(context, lineWidth);
        CGContextStrokePath(context);
        
        //绘制线框
        rect = CGRectMake(CGRectGetMaxX(rect)-lineWidth/2, CGRectGetMinY(rect)+lineWidth/2, self.width-CGRectGetWidth(rect), self.height-lineWidth);
        CGContextSetStrokeColorWithColor(context, self.renderColor.CGColor);
        CGContextSetLineWidth(context, lineWidth);
        CGContextStrokeRect(context, rect);
    }
    else
    {
        rect = CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetMaxY(self.anchorFrame)-CGRectGetMinY(self.frame));
        CGContextMoveToPoint(context, CGRectGetMinX(rect) + cornerRadius, CGRectGetMinY(rect));
        CGContextAddArc(context, CGRectGetMaxX(rect) - cornerRadius, CGRectGetMinY(rect) + cornerRadius, cornerRadius, 3 * M_PI / 2, 0, 0);
        CGContextAddLineToPoint(context, CGRectGetMaxX(rect), CGRectGetMaxY(rect));
        CGContextAddLineToPoint(context, CGRectGetMinX(rect), CGRectGetMaxY(rect));
        CGContextAddArc(context, CGRectGetMinX(rect) + cornerRadius, CGRectGetMinY(rect) + cornerRadius, cornerRadius, M_PI, 3 * M_PI / 2, 0);
        CGContextFillPath(context);
        
        CGContextMoveToPoint(context, self.isReverse == NO ? CGRectGetMaxX(rect) - 10 : CGRectGetMinX(rect)+5, CGRectGetMinY(rect) + cornerRadius);
        CGContextAddLineToPoint(context, self.isReverse == NO ? CGRectGetMaxX(rect) - 10 : CGRectGetMinX(rect)+5, CGRectGetMaxY(rect) - cornerRadius);
        CGContextMoveToPoint(context, self.isReverse == NO ? CGRectGetMaxX(rect) - 5 : CGRectGetMinX(rect)+10, CGRectGetMinY(rect) + cornerRadius);
        CGContextAddLineToPoint(context, self.isReverse == NO ? CGRectGetMaxX(rect) - 5 : CGRectGetMinX(rect)+10, CGRectGetMaxY(rect) - cornerRadius);
        CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
        CGContextSetLineWidth(context, lineWidth);
        CGContextStrokePath(context);
        
        rect = CGRectMake(lineWidth/2, CGRectGetMaxY(rect)-lineWidth/2, self.width-lineWidth, self.height-CGRectGetHeight(rect));
        CGContextSetStrokeColorWithColor(context, self.renderColor.CGColor);
        CGContextSetLineWidth(context, lineWidth);
        CGContextStrokeRect(context, rect);
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint tapPoint = [touch locationInView:self];
    if ((self.type == EFormControlViewTypeRow && (self.isReverse == NO ? tapPoint.y > self.height-60 : tapPoint.y < 60))
        || (self.type == EFormControlViewTypeCol && (self.isReverse == NO ? tapPoint.x > self.width-60 : tapPoint.x < 60)))
    {
        prevPoint = [touch locationInView:self.superview];
        [self.delegate formResizeCtrlViewSizeChangeBegin:self];
        resizeing = YES;
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (resizeing == YES)
    {
        CGFloat resizeValue = 0;
        UITouch *touch = [touches anyObject];
        CGPoint tapPoint = [touch locationInView:self.superview];
        if (self.type == EFormControlViewTypeRow)
        {
            resizeValue = self.isReverse == NO ? tapPoint.y-prevPoint.y : prevPoint.y-tapPoint.y;
            CGRect newFrame = self.frame;
            newFrame.size.height += resizeValue;
            if (newFrame.size.height >= FORMVIEW_CELL_MIN_H && newFrame.size.height <= FORMVIEW_CELL_MAX_H)
            {
                prevPoint = tapPoint;
                self.frame = newFrame;
                self.anchorFrame = CGRectMake(self.anchorFrame.origin.x, self.anchorFrame.origin.y, self.anchorFrame.size.width, self.anchorFrame.size.height+resizeValue);
                self.contentSize = CGSizeMake(self.contentSize.width, self.contentSize.height+resizeValue);
                [self.delegate formResizeCtrlView:self sizeChangeWithOffset:resizeValue];
            }
        }
        else
        {
            resizeValue = self.isReverse == NO ? tapPoint.x-prevPoint.x : prevPoint.x-tapPoint.x;
            CGRect newFrame = self.frame;
            newFrame.size.width += resizeValue;
            if (newFrame.size.width >= FORMVIEW_CELL_MIN_W && newFrame.size.width <= FORMVIEW_CELL_MAX_W)
            {
                prevPoint = tapPoint;
                self.frame = newFrame;
                self.anchorFrame = CGRectMake(self.anchorFrame.origin.x, self.anchorFrame.origin.y, self.anchorFrame.size.width+resizeValue, self.anchorFrame.size.height);
                self.contentSize = CGSizeMake(self.contentSize.width+resizeValue, self.contentSize.height);
                [self.delegate formResizeCtrlView:self sizeChangeWithOffset:resizeValue];
            }
        }
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self touchesEnded:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    resizeing = NO;
    [self.delegate formResizeCtrlViewSizeChangeEnd:self];
}


@end

/**
 *  CResizeableFormView
 */

@interface CResizeableFormView() <CFreezeFormViewDelegate, CFormResizeCtrlViewDelegate>

@property (nonatomic, retain) UIScrollView *scrollView;

@property (nonatomic, retain) CFormResizeCtrlView *resizeCtrlView;
@property (nonatomic, retain) CFormCellIndex *curResizeCellIndex;

@property (nonatomic, assign) BOOL showCtrlView;

@end

@implementation CResizeableFormView
{
    CFreezeFormView *_leftControlView;
    CFreezeFormView *_topControlView;
    
    CFreezeFormView *_formView;
}

@synthesize formView = _formView;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        _resizeable = YES;
        
        self.scrollView = [[[UIScrollView alloc] initWithFrame:self.bounds] autorelease_mm];
        self.scrollView.showsHorizontalScrollIndicator = NO;
        self.scrollView.showsVerticalScrollIndicator = NO;
        self.scrollView.contentSize = CGSizeMake(self.width, self.height);
        self.scrollView.alwaysBounceVertical = YES;
//        self.scrollView.alwaysBounceHorizontal = YES;
        self.scrollView.delegate = self;
        self.scrollView.pagingEnabled = NO;
        [self addSubview:self.scrollView];
        
        self.edgeInsets = UIEdgeInsetsMake(CONTROL_MARGIN, CONTROL_MARGIN, CONTROL_MARGIN, CONTROL_MARGIN);
        
        _formView = [[[CFreezeFormView alloc] initWithFrame:CGRectMake(self.edgeInsets.left, self.edgeInsets.top, self.width-self.edgeInsets.left-self.edgeInsets.right, self.height-self.edgeInsets.top-self.edgeInsets.bottom)] autorelease_mm];
        _formView.delegate = self;
        [self.scrollView addSubview:_formView];

        _leftControlView = [[[CFreezeFormView alloc] initWithFrame:CGRectMake(-CONTROL_SIZE, self.edgeInsets.top, CONTROL_SIZE, self.formView.height)] autorelease_mm];
        _leftControlView.delegate = self;
        _leftControlView.style = EFreezeFormStyleNone;
        _leftControlView.borderCornerRadius = CONTROL_SIZE/2;
        [self.scrollView addSubview:_leftControlView];
        
        _topControlView = [[[CFreezeFormView alloc] initWithFrame:CGRectMake(self.edgeInsets.left, -CONTROL_SIZE, self.formView.width, CONTROL_SIZE)] autorelease_mm];
        _topControlView.delegate = self;
        _topControlView.borderCornerRadius = CONTROL_SIZE/2;
        _topControlView.style = EFreezeFormStyleNone;
        [self.scrollView addSubview:_topControlView];
    }
    return self;
}

- (CGRect)contentFrame
{
    CGRect frame = CGRectMake(self.edgeInsets.left, self.edgeInsets.top, self.width-self.edgeInsets.left-self.edgeInsets.right, self.height-self.edgeInsets.top-self.edgeInsets.bottom);
    return CGRectInset(frame, self.formView.borderSize, self.formView.borderSize);
}

- (void)dealloc
{
    _formView.delegate = nil;
    [_formView removeFromSuperview];
    [_curResizeCellIndex release];
    [super dealloc];
}

- (void)didMoveToSuperview
{
    [super didMoveToSuperview];
    if (self.superview != nil)
    {
        [self reload];
    }
}

- (void)setEdgeInsets:(UIEdgeInsets)edgeInsets
{
    _edgeInsets = edgeInsets;
    [self updateContentFrame];
}

- (void)reload
{
    [self cancelResize];
    
    self.formView.rowNum = self.rowNum;
    self.formView.colNum = self.colNum;
    self.formView.freezeTopRowNum = self.freezeTopRowNum;
    self.formView.freezeColNum = self.freezeColNum;
    self.formView.freezeBottomRowNum = self.freezeBottomRowNum;
    [self.formView reload];
    
    _leftControlView.rowNum = self.formView.rowNum;
    _leftControlView.colNum = 1;
    _leftControlView.freezeTopRowNum = self.formView.freezeTopRowNum;
    _leftControlView.freezeBottomRowNum = self.freezeBottomRowNum;
    [_leftControlView reload];
    
    _topControlView.rowNum = 1;
    _topControlView.colNum = self.formView.colNum;
    _topControlView.freezeColNum = self.formView.freezeColNum;
    [_topControlView reload];
}

- (void)cancelResize
{
    _leftControlView.curSelectedIndex = nil;
    _topControlView.curSelectedIndex = nil;
    self.resizeCtrlView.hidden = YES;
    self.curResizeCellIndex = nil;
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
    self.scrollView.frame = self.bounds;
    self.scrollView.contentSize = CGSizeMake(self.width, self.height);
    [self updateContentFrame];
}

- (void)scrollToIndex:(CFormCellIndex *)index animated:(BOOL)animated
{
    [self.formView scrollToIndex:index animated:animated];
}

- (void)setResizeable:(BOOL)resizeable
{
    if (_resizeable == resizeable)
    {
        return;
    }
    
    _resizeable = resizeable;
    if (_resizeable == YES)
    {
        self.scrollView.alwaysBounceVertical = YES;
    }
    else
    {
        self.showCtrlView = NO;
        self.scrollView.alwaysBounceVertical = NO;
    }
}

- (void)setCurSelectedIndex:(CFormCellIndex *)curSelectedIndex
{
    self.formView.curSelectedIndex = curSelectedIndex;
}

- (CFormCellIndex *)curSelectedIndex
{
    return self.formView.curSelectedIndex;
}

- (CGSize)calculateOtherCellHeightAtIndex:(CFormCellIndex *)index
{
    CGSize maxHeightSize = CGSizeZero;
    for(NSInteger i = 0; i < self.colNum; i++) {
        if (i != index.col) {
            CFormCellIndex *otherIndex = [CFormCellIndex indexWithtRow:index.row col:i];
            CFormCellView *cell = [self.formView cellAtIndex:otherIndex];
            if (![cell isKindOfClass: [CFormSelectorCellView class]]) {
                //修复选择框 CELL 内图标偏移.
                CGSize otherSize = [self recalculateCellSizeAtIndex:otherIndex];
                if (otherSize.height > maxHeightSize.height) {
                    maxHeightSize = otherSize;
                }
            }
        }
    }
    return maxHeightSize;
}

- (void)fitCellSizeAtIndex:(CFormCellIndex *)index
{
    //对当前 CELL 的高度与同一行的最大高度进行比较,取得最大的高度作为行高.
    CGSize fitSize = [self recalculateCellSizeAtIndex:index];
    CGSize otherMaxHeightSize = [self calculateOtherCellHeightAtIndex:index];
    if (otherMaxHeightSize.height > fitSize.height) {
        fitSize.height = otherMaxHeightSize.height;
    }
    if (fitSize.height + 2*FORMVIEW_CELL_MARGIN_X  < FORMVIEW_DEF_ROW_H) {
        fitSize.height = FORMVIEW_DEF_ROW_H - 2*FORMVIEW_CELL_MARGIN_X;
    }
    
    CFormCellView *cell = [self.formView cellAtIndex:index];
    if (fitSize.width != cell.textLable.width)
    {
//        [self.formView setWidth:curSize.width+2*FORMVIEW_CELL_MARGIN_X forCol:index.col animated:YES];
//        [_topControlView setWidth:fitSize.width+2*FORMVIEW_CELL_MARGIN_X forCol:index.col animated:NO];
        if ([self.delegate respondsToSelector:@selector(resizeableFormView:colAtIndex:widthDidChange:)])
        {
            [self.delegate resizeableFormView:self colAtIndex:index.col widthDidChange:fitSize.width+2*FORMVIEW_CELL_MARGIN_X];
        }
    }
    if (fitSize.height != cell.textLable.height)
    {
        [self.formView setHeight:fitSize.height+2*FORMVIEW_CELL_MARGIN_Y forRow:index.row animated:YES];
        [_leftControlView setHeight:fitSize.height+2*FORMVIEW_CELL_MARGIN_Y forRow:index.row animated:NO];
        if ([self.delegate respondsToSelector:@selector(resizeableFormView:rowAtIndex:heightDidChange:)])
        {
            [self.delegate resizeableFormView:self rowAtIndex:index.row heightDidChange:fitSize.height+2*FORMVIEW_CELL_MARGIN_Y];
        }
    }
    
    [self scrollToIndex:index animated:YES];
}

- (CGSize)recalculateCellSizeAtIndex:(CFormCellIndex *)index
{   //由于当前设计的 CELL 的宽度在初次加载后不再动态变化,因此注释掉关于宽度调整的代码.
//    CGFloat maxW = FORMVIEW_CELL_MAX_W-2*FORMVIEW_CELL_MARGIN_X;
    CGFloat maxH = FORMVIEW_CELL_MAX_H-2*FORMVIEW_CELL_MARGIN_Y;
    CFormCellView *cell = [self.formView cellAtIndex:index];
    if (cell != nil)
    {
        CGSize curSize = [cell.textLable.text stringSizeWithFont:cell.textLable.font forConstrainSize:CGSizeMake(cell.textLable.width, maxH)];
//        if (curSize.height <= orgSize.height && curSize.width <= orgSize.width)
//        {
//            curSize = orgSize;
//        }
        // 如果当前需要的尺寸大于显示尺寸，则尝试增加cell的尺寸
        if (curSize.height > cell.textLable.height)
        {
            // 优先增加宽度
//            if (curSize.width < maxW)
//            {
//                CGFloat oldWidth = 0.0;
//                while (curSize.width < maxW) {
//                    oldWidth = curSize.width;
//                    curSize.width += DEF_FORM_CELL_FONT_SIZE;
//                    curSize = [cell.textLable.text stringSizeWithFont:cell.textLable.font forConstrainSize:CGSizeMake(curSize.width, maxH)];
//                    if (curSize.height <= cell.textLable.height) {
//                        break;
//                    }
//                    else if (curSize.width <= oldWidth) {
//                        curSize.width = oldWidth + DEF_FORM_CELL_FONT_SIZE;
//                    }
//                }
//                if (curSize.width > maxW) {
//                    curSize.width = maxW;
//                    curSize = [cell.textLable.text stringSizeWithFont:cell.textLable.font forConstrainSize:CGSizeMake(curSize.width, maxH)];
//                }
//            }
            // 如果依然不能显示完全，增加高度
            if (curSize.height > cell.textLable.height)
            {
                if (curSize.height > maxH) {
                    curSize.height = maxH;
                }
            }
            else
            {
                curSize.height = cell.textLable.height;
            }
        }
        // 如果当前的高度不大于于原始的高度，则尝试调小cell的宽度，
//        else if (curSize.height <= orgSize.height-DEF_FORM_CELL_FONT_SIZE)
//        {
//            NSInteger orgLineNumber = orgSize.height / (DEF_FORM_CELL_FONT_SIZE+2);
//            curSize.height = orgSize.height;
//            CGSize oneLineSize = [cell.textLable.text stringSizeWithFont:cell.textLable.font];
//            curSize.width = oneLineSize.width/orgLineNumber + 2*orgLineNumber;
//            if (curSize.width < orgSize.width) {
//                curSize.width = orgSize.width;
//            }
//        }
        
        // 适当扩大尺寸，防止浮点数精确位数导致的错误
        curSize = CGSizeMake(ceil(curSize.width), ceil(curSize.height));
        return curSize;
    }
    return CGSizeZero;
}

- (CGFloat)calculateRealContentHeight
{
    CGFloat height = 0;
    for (NSUInteger row=0; row<self.rowNum; row++)
    {
        height += [self.formView heightForRow:row];
    }
    return height+self.edgeInsets.top+self.edgeInsets.bottom+self.formView.borderSize*2;
}

#pragma mark show or hide control view

- (void)resizeCtrlAnchorViewFrameChange
{
    CFormCellView *cell = [self.resizeCtrlView.type == EFormControlViewTypeRow ? _leftControlView : _topControlView cellAtIndex:self.curResizeCellIndex];
    if (cell == nil)
    {
        self.resizeCtrlView.anchorFrame = CGRectZero;
    }
    else
    {
        CGRect cellFrame = [self convertRect:cell.bounds fromView:cell];
        self.resizeCtrlView.anchorFrame = CGRectInset(cellFrame, self.resizeCtrlView.type == EFormControlViewTypeRow ? -_leftControlView.borderSize : 0, self.resizeCtrlView.type == EFormControlViewTypeRow ? 0 : -_topControlView.borderSize);
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.scrollView && self.resizeCtrlView.hidden == NO)
    {
        [self resizeCtrlAnchorViewFrameChange];
        
        if (self.resizeCtrlView.type == EFormControlViewTypeRow)
        {
            if (self.curResizeCellIndex.row < self.freezeTopRowNum || self.curResizeCellIndex.row > self.rowNum-self.freezeBottomRowNum-1)
            {
                self.resizeCtrlView.maskFrame = _leftControlView.frame;
            }
            else
            {
                self.resizeCtrlView.maskFrame = CGRectInset([self convertRect:[_leftControlView notFreezeContentFrame] fromView:_leftControlView], -_leftControlView.borderSize, -_leftControlView.borderSize);
            }
        }
        else
        {
            if (self.curResizeCellIndex.col < self.freezeColNum)
            {
                self.resizeCtrlView.maskFrame = _topControlView.frame;
            }
            else
            {
                self.resizeCtrlView.maskFrame = CGRectInset([self convertRect:[_topControlView notFreezeContentFrame] fromView:_topControlView], -_topControlView.borderSize, -_topControlView.borderSize);
            }
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (scrollView == self.scrollView)
    {
        if (self.scrollView.contentOffset.x < -50 || self.scrollView.contentOffset.y < -50)
        {
            self.showCtrlView = !self.showCtrlView;
        }
//        else if ((self.scrollView.contentOffset.x > CONTROL_SIZE || self.scrollView.contentOffset.y > CONTROL_SIZE) && self.showCtrlView == YES)
//        {
//            self.showCtrlView = NO;
//        }
    }
}

/**
 *  调整表格以及上方和左方的间距调试表格的frame
 */
- (void)updateContentFrame
{
    if (self.showCtrlView == YES)
    {
        _leftControlView.frame = CGRectMake(self.edgeInsets.left, self.edgeInsets.top+CONTROL_MARGIN+CONTROL_SIZE, _leftControlView.width, self.height-CONTROL_MARGIN-CONTROL_SIZE-self.edgeInsets.top-self.edgeInsets.bottom);
        _topControlView.frame = CGRectMake(self.edgeInsets.left+CONTROL_SIZE+CONTROL_MARGIN, self.edgeInsets.top, self.width-CONTROL_MARGIN-CONTROL_SIZE-self.edgeInsets.left-self.edgeInsets.right, _topControlView.height);
        self.formView.frame = CGRectMake(_topControlView.left, _leftControlView.top, _topControlView.width, _leftControlView.height);
//        self.formView.frame = CGRectMake(2*CONTROL_MARGIN+CONTROL_SIZE, 2*CONTROL_MARGIN+CONTROL_SIZE, self.width-3*CONTROL_MARGIN-CONTROL_SIZE, self.height-3*CONTROL_MARGIN-CONTROL_SIZE);
//        _leftControlView.frame = CGRectMake(CONTROL_MARGIN, self.formView.top, _leftControlView.width, self.formView.height);
//        _topControlView.frame = CGRectMake(self.formView.left, CONTROL_MARGIN, self.formView.width, _topControlView.height);
    }
    else
    {
        self.formView.frame = CGRectMake(self.edgeInsets.left, self.edgeInsets.top, self.width-self.edgeInsets.left-self.edgeInsets.right, self.height-self.edgeInsets.top-self.edgeInsets.bottom);
        _leftControlView.frame = CGRectMake(self.edgeInsets.left>CONTROL_MARGIN ? -CONTROL_SIZE : -CONTROL_SIZE-(CONTROL_MARGIN-self.edgeInsets.left), self.formView.top, _leftControlView.width, self.formView.height);
        _topControlView.frame = CGRectMake(self.formView.left, self.edgeInsets.top>CONTROL_MARGIN ? -CONTROL_SIZE : -CONTROL_SIZE-(CONTROL_MARGIN-self.edgeInsets.top), self.formView.width, _topControlView.height);
//        self.formView.frame = CGRectMake(CONTROL_MARGIN, CONTROL_MARGIN, self.width-2*CONTROL_MARGIN, self.height-2*CONTROL_MARGIN);
//        _leftControlView.frame = CGRectMake(-_leftControlView.width, self.formView.top, _leftControlView.width, self.formView.height);
//        _topControlView.frame = CGRectMake(self.formView.left, -_topControlView.height, self.formView.width, _topControlView.height);
    }
}

- (void)setShowCtrlView:(BOOL)showCtrlView
{
    _showCtrlView = showCtrlView;
    if (showCtrlView == NO)
    {
        [self cancelResize];
    }
    [UIView animateWithDuration:.25 animations:^{
        [self updateContentFrame];
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark form view delegate

- (CGFloat)freezeFormView:(CFreezeFormView *)view heightForRow:(NSUInteger)row
{
    if (view == _topControlView)
    {
        return CONTROL_SIZE-2;
    }
    else
    {
        if ([self.delegate respondsToSelector:@selector(freezeFormView:heightForRow:)])
        {
            return [self.delegate freezeFormView:view heightForRow:row];
        }
        return FORMVIEW_DEF_ROW_H;
    }
}

- (CGFloat)freezeFormView:(CFreezeFormView *)view widthForCol:(NSUInteger)col
{
    if (view == _leftControlView)
    {
        return CONTROL_SIZE-2;
    }
    else
    {
        if ([self.delegate respondsToSelector:@selector(freezeFormView:widthForCol:)])
        {
            return [self.delegate freezeFormView:view widthForCol:col];
        }
        return FORMVIEW_DEF_COL_W;
    }
}

- (CFormCellView *)freezeFormView:(CFreezeFormView *)view cellAtIndex:(CFormCellIndex *)index
{
    if (view == self.formView)
    {
        return [self.delegate freezeFormView:view cellAtIndex:index];
    }
    
    CFormCellView *cell = [view dequeueReusableCellWithIdentifier:@"cell" forIndex:index];
    if (cell == nil)
    {
        cell = [[[CFormCellView alloc] initWithReuseIdentifier:@"cell"] autorelease_mm];
    }
    cell.highlightable = NO;
    if (view == _leftControlView)
    {
        cell.textLable.text = [NSString stringWithFormat:@"%lu", ToULong index.row];
        cell.textLable.numberOfLines = 1;
        cell.textLable.adjustsFontSizeToFitWidth = YES;
        cell.borderMask = index.row < view.rowNum-1 ? EFormBorderBottom: EFormBorderNone;
    }
    else
    {
        cell.textLable.text = [NSString stringWithFormat:@"%lu", ToULong index.col];
        cell.borderMask = index.col < view.colNum-1 ? EFormBorderRight: EFormBorderNone;
    }
    
    return cell;
}

- (void)freezeFormView:(CFreezeFormView *)view didClickCellAtIndex:(CFormCellIndex *)index
{
    if (view == self.formView)
    {
        [self.delegate freezeFormView:view didClickCellAtIndex:index];
        [self cancelResize];
    }
    else
    {
        if (self.resizeCtrlView == nil)
        {
            self.resizeCtrlView = [[[CFormResizeCtrlView alloc] initWithFrame:CGRectZero] autorelease_mm];
            self.resizeCtrlView.delegate = self;
            [self addSubview:self.resizeCtrlView];
        }
        self.curResizeCellIndex = index;
        self.resizeCtrlView.hidden = NO;
        CFormCellView *cell = [view cellAtIndex:index];
        CGRect cellFrame = [self convertRect:cell.bounds fromView:cell];
        if (view == _leftControlView)
        {
            self.resizeCtrlView.isReverse = index.row == self.rowNum-1;
            self.resizeCtrlView.type = EFormControlViewTypeRow;
            if (index.row < self.freezeTopRowNum || index.row > self.rowNum-self.freezeBottomRowNum-1)
            {
                self.resizeCtrlView.maskFrame = _leftControlView.frame;
            }
            else
            {
                self.resizeCtrlView.maskFrame = CGRectInset([self convertRect:[_leftControlView notFreezeContentFrame] fromView:_leftControlView], -_leftControlView.borderSize, -_leftControlView.borderSize);
            }
            _topControlView.curSelectedIndex = nil;
            self.resizeCtrlView.contentSize = CGSizeMake([self.formView contentDisplaySize].width+view.borderSize*2, cellFrame.size.height);
            self.resizeCtrlView.anchorFrame = CGRectInset(cellFrame, -_leftControlView.borderSize, 0);
        }
        else
        {
            self.resizeCtrlView.isReverse = index.col == self.colNum-1;
            self.resizeCtrlView.type = EFormControlViewTypeCol;
            if (index.col < self.freezeColNum)
            {
                self.resizeCtrlView.maskFrame = _topControlView.frame;
            }
            else
            {
                self.resizeCtrlView.maskFrame = CGRectInset([self convertRect:[_topControlView notFreezeContentFrame] fromView:_topControlView], -_topControlView.borderSize, -_topControlView.borderSize);
            }
            _leftControlView.curSelectedIndex = nil;
            self.resizeCtrlView.contentSize = CGSizeMake(cellFrame.size.width, [self.formView contentDisplaySize].height+view.borderSize*2);
            self.resizeCtrlView.anchorFrame = CGRectInset(cellFrame, 0, -_topControlView.borderSize);
        }
    }
}

- (void)freezeFormView:(CFreezeFormView *)view contentOffsetChange:(CGPoint)contentOffset
{
    if (view == self.formView)
    {
        [_topControlView scrollToFormContentOffset:CGPointMake(contentOffset.x, 0)];
        [_leftControlView scrollToFormContentOffset:CGPointMake(0, contentOffset.y)];
    }
    else if (view == _topControlView)
    {
        [self.formView scrollToFormContentOffset:CGPointMake(contentOffset.x, [self.formView formContentOffset].y)];
    }
    else if (view == _leftControlView)
    {
        [self.formView scrollToFormContentOffset:CGPointMake([self.formView formContentOffset].x, contentOffset.y)];
    }
    
    if (self.curResizeCellIndex != nil)
    {
        [self resizeCtrlAnchorViewFrameChange];
    }
}

- (void)freezeFormView:(CFreezeFormView *)view contentSizeChange:(CGSize)contentSize
{
    if (view == self.formView)
    {
        if (self.curResizeCellIndex != nil)
        {
            if (self.resizeCtrlView.type == EFormControlViewTypeRow)
            {
                self.resizeCtrlView.contentSize = CGSizeMake(contentSize.width+view.borderSize*2, self.resizeCtrlView.contentSize.height);
            }
            else
            {
                self.resizeCtrlView.contentSize = CGSizeMake(self.resizeCtrlView.contentSize.width, contentSize.height+view.borderSize*2);
            }
        }
    }
}

- (void)freezeFormViewDidEndScroll:(CFreezeFormView *)view
{
    if ([self.delegate respondsToSelector:@selector(resizeableFormViewDidEndScroll:)])
    {
        [self.delegate resizeableFormViewDidEndScroll:self];
    }
}

- (void)formResizeCtrlViewSizeChangeBegin:(CFormResizeCtrlView *)ctrlView
{
    if ([self.delegate respondsToSelector:@selector(resizeableFormViewDidStartResize:)])
    {
        [self.delegate resizeableFormViewDidStartResize:self];
    }
}

- (void)formResizeCtrlViewSizeChangeEnd:(CFormResizeCtrlView *)ctrlView
{
    if (ctrlView.type == EFormControlViewTypeRow)
    {
        if ([self.delegate respondsToSelector:@selector(resizeableFormView:rowAtIndex:heightDidChange:)])
        {
            CGFloat height = [_leftControlView heightForRow:self.curResizeCellIndex.row];
            [self.delegate resizeableFormView:self rowAtIndex:self.curResizeCellIndex.row heightDidChange:height];
        }
    }
    else if (ctrlView.type == EFormControlViewTypeCol)
    {
        if ([self.delegate respondsToSelector:@selector(resizeableFormView:colAtIndex:widthDidChange:)])
        {
            CGFloat width = [_topControlView widthForCol:self.curResizeCellIndex.col];
            [self.delegate resizeableFormView:self colAtIndex:self.curResizeCellIndex.col widthDidChange:width];
        }
    }
    if ([self.delegate respondsToSelector:@selector(resizeableFormViewDidEndResize:)])
    {
        [self.delegate resizeableFormViewDidEndResize:self];
    }
}

- (void)formResizeCtrlView:(CFormResizeCtrlView *)ctrlView sizeChangeWithOffset:(CGFloat)sizeOffset
{
    if (ctrlView.type == EFormControlViewTypeRow)
    {
        CGFloat height = [_leftControlView heightForRow:self.curResizeCellIndex.row];
        [_leftControlView setHeight:height+sizeOffset forRow:self.curResizeCellIndex.row animated:NO];
        [self.formView setHeight:height+sizeOffset forRow:self.curResizeCellIndex.row animated:NO];
        
        if (self.curResizeCellIndex.row == self.rowNum-1)
        {
            [self resizeCtrlAnchorViewFrameChange];
        }
    }
    else
    {
        CGFloat width = [_topControlView widthForCol:self.curResizeCellIndex.col];
        [_topControlView setWidth:width+sizeOffset forCol:self.curResizeCellIndex.col animated:NO];
        [self.formView setWidth:width+sizeOffset forCol:self.curResizeCellIndex.col animated:NO];
    }
}



@end
